import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { httpConfig } from './config.ts'
import { Message } from './resetMessage'
import { ElMessageBox } from 'element-plus'
import router from '../router'
import JSONbig from 'json-bigint'//解决超过 16 位数字精度丢失问题
class HttpRequest {
    private readonly baseUrl: string;
    private readonly timeout: number;
    constructor() {
        this.baseUrl = httpConfig.baseURL
        this.timeout = httpConfig.timeout
    }

    getInsideConfig(options) {
        const config = {
            baseURL: this.baseUrl,// 所有的请求地址前缀部分(没有后端请求不用写)  
            timeout: this.timeout, // 请求超时时间(毫秒)
            withCredentials: true,// 异步请求携带cookie
            headers: {
                // 'Content-Type': options.formType?'multipart/form-data':'application/json',
                'Content-Type': 'application/json',
                'token': localStorage.getItem('Token'),
            },
            transformResponse: [function (data: any) {
                try {
                    // 如果转换成功则返回转换的数据结果
                    //  JSONbig.parse(data)
                    return JSON.parse(JSON.stringify(JSONbig.parse(data)))
                } catch (err) {
                    // 如果转换失败，则包装为统一数据格式并返回
                    return {
                        data
                    }
                }
            }]
        }
        return config
    }

    // 请求拦截
    interceptors(instance: AxiosInstance,) {
        instance.interceptors.request.use(config => {
            // 添加全局的loading..
            // 请求头携带token

            return config
        }, (error: any) => {
            return Promise.reject(error)
        })
        //响应拦截
        instance.interceptors.response.use(res => {
            //返回数据
           
            const { data } = res
            console.log(data.code);
           if(data.code){
            let codeList = ['2000001', '2000002', '2000003', '2000004', '2000005']
            if (codeList.some(item => data.code == item)) {
                if (!localStorage.getItem('msgBox')) {
                    localStorage.setItem('msgBox', 'true')
                    ElMessageBox.alert('当前登录信息已失效，请重新登录', '提示', {
                        // if you want to disable its autofocus
                        // autofocus: false,
                        confirmButtonText: '确定',
                        callback: () => {
                            router.push('/')

                        },
                    })
                }
                return Promise.reject(data)
            }
            if (data.code != '000000') {
                Message({ type: 'error', message: data.msg })
                return Promise.reject(data)
            }
            return data.data
           }else{
            return data.data
           }
            
        }, (error: any) => {
            Message({ type: 'error', message: '请求超时，请重试' })
            return Promise.reject(error)
        })
    }

    request(options: AxiosRequestConfig) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(options), options)

        this.interceptors(instance)
        return instance(options)
    }
}

const http = new HttpRequest()
export default http
